package com.ja.openchat.viewmodels;

import android.app.Application;
import android.os.Bundle;
import android.text.TextUtils;

import com.google.gson.JsonObject;
import com.ja.openchat.R;
import com.ja.openchat.ui.MainActivity;
import com.ja.openchat.ui.login.SetNickNameFragment;
import com.zy.openchat.App;
import com.zy.openchat.core.manager.AuthUserManager;
import com.zy.openchat.core.manager.TelegramManager;
import com.zy.openchat.core.manager.TgEvent;
import com.zy.openchat.core.manager.TgResponse;
import com.zy.openchat.core.manager.TgResultBlock;
import com.zy.openchat.core.model.user.UserInfo;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Map;
import java.util.concurrent.TimeUnit;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableField;
import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import me.goldze.mvvmhabit.base.BaseViewModel;
import me.goldze.mvvmhabit.binding.command.BindingAction;
import me.goldze.mvvmhabit.binding.command.BindingCommand;
import me.goldze.mvvmhabit.bus.Messenger;
import me.goldze.mvvmhabit.bus.event.SingleLiveEvent;
import me.goldze.mvvmhabit.utils.KLog;

import static com.blankj.utilcode.util.StringUtils.getString;


public class LoginPhoneCodeViewModel extends BaseViewModel {
    //手机号的绑定
    public ObservableField<String> phone = new ObservableField<>("");
    private String curCountryCode;
    private String curPhone;
    public static final String TOKEN_PHONECODEVIEWMODEL_FINISH = "token_phonecodeviewmodel_finish";

    //封装一个界面发生改变的观察者
    public UIChangeObservable uc = new UIChangeObservable();


    public class UIChangeObservable {
        //倒计时观察者
        public SingleLiveEvent<String> timerEvent = new SingleLiveEvent<>();
    }

    public LoginPhoneCodeViewModel(@NonNull Application application) {
        super(application);
        Messenger.getDefault().register(this, TOKEN_PHONECODEVIEWMODEL_FINISH, () -> finish());
    }

    //重新发送的点击事件
    public BindingCommand confirmOnClickCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            getPhoneCode(curCountryCode,curPhone);
        }
    });

    public void setData(Bundle bundle) {
        if (bundle != null) {
            curCountryCode = bundle.getString("code");
            curPhone = bundle.getString("phone");
            phone.set(curCountryCode + " " + curPhone);
            getPhoneCode(curCountryCode,curPhone);
        }
    }

    public void check(String smsCode) {
        showProgress();
        TelegramManager.getTelegramManager().checkAuthenticationCode(getApplication(), smsCode, new TgResultBlock<TgResponse>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                hideProgress();
                if (!obj.ok) {
                    if (obj.errCode == 420) {//验证码错误次数过多，请5分钟后重新登录
                        showErrorTip(getString(R.string.invalid_sms_code_is_block));
                        finish();
                    } else {
                        showErrorTip(getString(R.string.invalid_sms_code));
                    }
                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {
                hideProgress();
                showErrorTip(getString(R.string.request_error));
            }
        });
    }



    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onTgEvent(final TgEvent tg_event) {
        switch (tg_event.event) {
            case EUser_Td_Register:
                Bundle bundle = new Bundle();
                bundle.putString("curCountryCode", curCountryCode);
                bundle.putString("curPhone", curPhone);
                startContainerActivity(SetNickNameFragment.class.getCanonicalName(), bundle);
                finish();
                break;
            case EUser_Td_Ready:
                //清理数据
                AuthUserManager.cleanDestroyFolder();
                //登录
                AuthUserManager.getAuthUserManager().login(String.format("%s%s", curCountryCode, curPhone), UserInfo.getUserInfo().data_directory);
                //跳转主页面
                startActivity(MainActivity.class);
                Messenger.getDefault().sendNoMsg(RegisterViewModel.TOKEN_REGISTERVIEWMODEL_FINISH);
                Messenger.getDefault().sendNoMsg(LoginViewModel.TOKEN_LOGINVIEWMODEL_FINISH);
                Messenger.getDefault().sendNoMsg(LoginByPhoneViewModel.TOKEN_LOGINBYPHONEVIEWMODEL_FINISH);
                finish();
                break;
            default:
                break;
        }
    }

    private void getPhoneCode(String countryCode,String phone) {
        UserInfo.getUserInfo().isPasswordLoginType = false;
        UserInfo.getUserInfo().isPasswordRegisterType = false;
        showProgress();
        TelegramManager.getTelegramManager().setAuthenticationPhoneNumber(getApplication(), String.format("+%s %s", countryCode, phone), new TgResultBlock<TgResponse>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                hideProgress();
                if (!obj.ok) {
                    //{"@type":"error","code":400,"message":"PASSWORD_VERIFY_INVALID","@extra":4}
                    //USER_PASSWORD_NEEDED 必须输入密码
//                        USERNAME_NOT_EXIST 用户名不存在
//                        USER_PASSWORD_NOT_SET 用户未设置密码
//                        PASSWORD_VERIFY_INVALID 密码校验错误
//                        IP_ADDRESS_BANNED 登录ip被禁用
//                        USER_BINDED_IP_ADDRESS 登录用户已经绑定ip
                    if (obj.errCode == 400) {
                        if ("400_IP_ADDRESS_BANNED".equals(obj.errString)) {
                            showErrorTip(App.getInstanse().getString(R.string.ip_ban_login));
                            return;
                        }
                        if ("400_USER_BINDED_IP_ADDRESS".equals(obj.errString)) {
                            showErrorTip(App.getInstanse().getString(R.string.ip_bind_login));
                            return;
                        }
                    }
                    if(!TextUtils.isEmpty(obj.errString)){
                        if(obj.errString.contains("INVITE_CODE_INVALID")){
                            showErrorTip(getString(R.string.account_not_registered));
                            return;
                        }
                        if(obj.errString.contains("PHONE_NUMBER_BANNED")){
                            showErrorTip(getString(R.string.account_banned));
                            return;
                        }
                    }
                    showErrorTip(getString(R.string.invalid_phone));
                }else{
                    startCountDown();
                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {
                hideProgress();
                showErrorTip(getString(R.string.request_error));
            }
        });
    }

    private void startCountDown(){
        addSubscribe(Flowable.intervalRange(0, 60, 0, 1, TimeUnit.SECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .doOnNext(aLong -> {
                    int time = (int) (59 - aLong);
                    KLog.d("aLong==" + time);
                    if (time > 0) {
                        uc.timerEvent.setValue(App.getInstanse().getString(R.string.resend_verify_code)+"（"+time+"）");
                    } else {
                        uc.timerEvent.setValue(App.getInstanse().getString(R.string.resend_verify_code));
                    }
                })
                .doOnComplete(() -> {
                    //倒计时完毕事件处理
                    KLog.d("doOnComplete==");
                    uc.timerEvent.setValue(App.getInstanse().getString(R.string.resend_verify_code));
                })
                .subscribe());
    }
}
